package com.example.materialcostsystembackend.service.impl;

import com.example.materialcostsystembackend.model.Part;
import com.example.materialcostsystembackend.repository.PartRepository;
import com.example.materialcostsystembackend.service.PartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PartServiceImpl implements PartService {

    @Autowired
    private PartRepository repository;

    @Override
    public void addPart(String name, String specification, String unit, Double price, int qty) {
        Optional<Part> existing = repository.findByNameAndSpecification(name, specification);
        if (existing.isPresent()) {
            Part part = existing.get();
            part.setQuantity(part.getQuantity() + qty);
            repository.save(part);
        } else {
            Part part = new Part();
            part.setName(name);
            part.setSpecification(specification);
            part.setUnit(unit);
            part.setPrice(price);
            part.setQuantity(qty);
            repository.save(part);
        }
    }

    @Override
    public List<Part> getAllParts() {
        return repository.findAll();
    }
}
